package com.education.ai.controller;

import com.education.ai.entity.TeachingPlan;
import com.education.ai.service.TeachingPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/api/teaching-plans")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true", exposedHeaders = "X-Total-Count")
public class TeachingPlanController {

    @Autowired
    private TeachingPlanService teachingPlanService;
    
    @PersistenceContext
    private EntityManager entityManager;

    @GetMapping
    public ResponseEntity<List<TeachingPlan>> getAllTeachingPlans(
            @RequestParam(required = false) String teacherId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "15") int size,
            HttpServletRequest request) {
        log.info("获取教学计划列表，教师ID：{}，页码：{}，每页数量：{}", teacherId, page, size);
        
        // 打印请求头信息，帮助调试跨域问题
        log.info("请求头Origin: {}", request.getHeader("Origin"));
        log.info("请求头Referer: {}", request.getHeader("Referer"));
        
        // 创建分页请求
        Pageable pageable = PageRequest.of(page, size);
        List<TeachingPlan> plans;
        long totalCount;
        
        if (teacherId != null && !teacherId.isEmpty()) {
            // 根据教师ID查询
            log.info("开始根据教师ID[{}]查询教学计划", teacherId);
            plans = teachingPlanService.findByTeacherId(teacherId, pageable);
            totalCount = teachingPlanService.countByTeacherId(teacherId);
            log.info("查询结果: 返回了{}条记录，总记录数：{}", plans.size(), totalCount);
            
            // 如果没有查询到记录，尝试使用原生SQL查询
            if (plans.isEmpty()) {
                log.warn("未查询到教师ID为[{}]的教学计划记录，尝试使用原生SQL查询", teacherId);
                try {
                    // 使用原生SQL查询
                    List<Object[]> records = entityManager.createNativeQuery(
                        "SELECT id, title, teacher_id, content, subject, grade, create_time FROM teaching_plans WHERE teacher_id = ?")
                        .setParameter(1, teacherId)
                        .getResultList();
                    
                    log.info("原生SQL查询结果: 返回了{}条记录", records.size());
                    
                    // 如果SQL能查到记录，手动构建TeachingPlan对象
                    if (!records.isEmpty()) {
                        plans = new ArrayList<>();
                        for (Object[] record : records) {
                            TeachingPlan plan = new TeachingPlan();
                            plan.setId(record[0] != null ? Long.valueOf(record[0].toString()) : null);
                            plan.setTitle((String) record[1]);
                            plan.setTeacherId((String) record[2]);
                            plan.setContent((String) record[3]);
                            plan.setSubject((String) record[4]);
                            plan.setGrade((String) record[5]);
                            // 处理日期
                            if (record[6] != null) {
                                if (record[6] instanceof Date) {
                                    plan.setCreateTime((Date) record[6]);
                                } else if (record[6] instanceof java.sql.Timestamp) {
                                    plan.setCreateTime(new Date(((java.sql.Timestamp) record[6]).getTime()));
                                }
                            }
                            plans.add(plan);
                        }
                        totalCount = records.size();
                        log.info("成功从原生SQL构建了{}条记录", plans.size());
                    }
                } catch (Exception e) {
                    log.error("原生SQL查询失败", e);
                }
            }
        } else {
            // 查询所有
            log.info("查询所有教学计划记录");
            plans = teachingPlanService.findAll(pageable);
            totalCount = teachingPlanService.count();
            log.info("查询结果: 返回了{}条记录，总记录数：{}", plans.size(), totalCount);
        }
        
        // 设置响应头，包含总记录数
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Total-Count", String.valueOf(totalCount));
        // 添加跨域访问控制头
        headers.add("Access-Control-Expose-Headers", "X-Total-Count");
        
        // 打印返回的数据
        if (!plans.isEmpty()) {
            for (TeachingPlan plan : plans) {
                log.info("返回记录: ID={}, 标题={}, 教师ID={}", plan.getId(), plan.getTitle(), plan.getTeacherId());
            }
        } else {
            log.warn("没有找到任何教学计划记录");
        }
        
        return ResponseEntity.ok()
                .headers(headers)
                .body(plans);
    }

    @GetMapping("/{id}")
    public ResponseEntity<TeachingPlan> getTeachingPlanById(@PathVariable Long id) {
        log.info("获取教学计划详情，ID: {}", id);
        return ResponseEntity.ok(teachingPlanService.findById(id));
    }

    @GetMapping("/subject/{subject}")
    public ResponseEntity<List<TeachingPlan>> getTeachingPlansBySubject(@PathVariable String subject) {
        log.info("获取学科教学计划列表: {}", subject);
        return ResponseEntity.ok(teachingPlanService.findBySubject(subject));
    }

    @GetMapping("/grade/{grade}")
    public ResponseEntity<List<TeachingPlan>> getTeachingPlansByGrade(@PathVariable String grade) {
        log.info("获取年级教学计划列表: {}", grade);
        return ResponseEntity.ok(teachingPlanService.findByGrade(grade));
    }

    @PostMapping
    public ResponseEntity<TeachingPlan> saveTeachingPlan(@RequestBody TeachingPlan teachingPlan) {
        log.info("保存教学计划: {}", teachingPlan.getTitle());
        return ResponseEntity.ok(teachingPlanService.save(teachingPlan));
    }

    @PutMapping("/{id}")
    public ResponseEntity<TeachingPlan> updateTeachingPlan(@PathVariable Long id, @RequestBody TeachingPlan teachingPlan) {
        log.info("更新教学计划，ID: {}", id);
        teachingPlan.setId(id);
        return ResponseEntity.ok(teachingPlanService.save(teachingPlan));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTeachingPlan(@PathVariable Long id) {
        log.info("删除教学计划，ID: {}", id);
        teachingPlanService.deleteById(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 保存前端设计的教学计划
     */
    @PostMapping("/save-design")
    public ResponseEntity<TeachingPlan> saveDesignedTeachingPlan(
            @RequestParam String subject,
            @RequestParam String grade,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String teacherId,
            @RequestBody String content) {
        log.info("保存前端设计的教学计划 - 学科: {}, 年级: {}, 教师ID: {}", subject, grade, teacherId);
        
        TeachingPlan plan = new TeachingPlan();
        plan.setSubject(subject);
        plan.setGrade(grade);
        plan.setTitle(title != null ? title : String.format("%s%s - 教学设计", grade, subject));
        plan.setContent(content);
        plan.setDuration(45); // 默认45分钟
        
        // 设置教师ID
        if (teacherId != null && !teacherId.isEmpty()) {
            plan.setTeacherId(teacherId);
        }
        
        return ResponseEntity.ok(teachingPlanService.save(plan));
    }

    /**
     * 获取模板教学计划
     */
    @GetMapping("/templates")
    public ResponseEntity<List<TeachingPlan>> getTeachingPlanTemplates() {
        log.info("获取教学计划模板列表");
        return ResponseEntity.ok(teachingPlanService.findTemplates());
    }

    /**
     * 调试端点：检查数据库中的教师教学计划记录
     */
    @GetMapping("/debug")
    public ResponseEntity<?> debugTeacherPlans(
            @RequestParam String teacherId) {
        try {
            log.info("调试: 直接从数据库查询教师[{}]的教学计划记录", teacherId);
            
            // 使用Repository直接查询
            List<TeachingPlan> plans = teachingPlanService.findByTeacherId(teacherId);
            log.info("教师[{}]的教学计划数量: {}", teacherId, plans.size());
            
            if (plans.isEmpty()) {
                log.warn("数据库中没有找到教师[{}]的教学计划记录", teacherId);
                
                // 查询数据库中的所有教学计划
                List<TeachingPlan> allPlans = teachingPlanService.findAll();
                log.info("数据库中共有{}条教学计划记录", allPlans.size());
                
                // 输出每条记录的teacherId
                for (TeachingPlan plan : allPlans) {
                    log.info("教学计划[{}] 教师ID: {}", plan.getId(), plan.getTeacherId());
                }
            } else {
                // 输出查询到的记录详情
                for (TeachingPlan plan : plans) {
                    log.info("找到教学计划: ID={}, 标题={}, 教师ID={}, 创建时间={}", 
                             plan.getId(), plan.getTitle(), plan.getTeacherId(), plan.getCreateTime());
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "教师ID: " + teacherId + ", 查询到记录数: " + plans.size());
            result.put("data", plans);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("调试查询失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("调试查询失败: " + e.getMessage());
        }
    }

    /**
     * 调试端点：使用原生SQL查询检查数据库
     */
    @GetMapping("/sql-debug")
    public ResponseEntity<?> sqlDebug(@RequestParam String teacherId) {
        try {
            log.info("执行原生SQL查询，检查教师[{}]的教学计划记录", teacherId);
            
            Map<String, Object> result = new HashMap<>();
            
            // 1. 查询表结构
            log.info("查询teaching_plans表结构");
            try {
                List<Object[]> columns = entityManager.createNativeQuery(
                    "SHOW COLUMNS FROM teaching_plans").getResultList();
                List<Map<String, Object>> columnInfo = new ArrayList<>();
                for (Object[] column : columns) {
                    Map<String, Object> col = new HashMap<>();
                    col.put("name", column[0]);
                    col.put("type", column[1]);
                    columnInfo.add(col);
                }
                result.put("tableStructure", columnInfo);
            } catch (Exception e) {
                log.error("查询表结构失败", e);
                result.put("tableStructureError", e.getMessage());
            }
            
            // 2. 直接使用SQL查询教师ID的记录
            log.info("使用SQL直接查询教师[{}]的记录", teacherId);
            try {
                List<Object[]> records = entityManager.createNativeQuery(
                    "SELECT id, title, teacher_id, create_time FROM teaching_plans WHERE teacher_id = ?")
                    .setParameter(1, teacherId)
                    .getResultList();
                
                List<Map<String, Object>> recordsList = new ArrayList<>();
                for (Object[] record : records) {
                    Map<String, Object> rec = new HashMap<>();
                    rec.put("id", record[0]);
                    rec.put("title", record[1]);
                    rec.put("teacher_id", record[2]);
                    rec.put("create_time", record[3]);
                    recordsList.add(rec);
                }
                result.put("records", recordsList);
                result.put("recordCount", records.size());
            } catch (Exception e) {
                log.error("SQL查询记录失败", e);
                result.put("recordsError", e.getMessage());
            }
            
            // 3. 查询所有记录的teacher_id
            log.info("查询所有教学计划记录的teacher_id");
            try {
                List<Object[]> allTeacherIds = entityManager.createNativeQuery(
                    "SELECT id, title, teacher_id FROM teaching_plans")
                    .getResultList();
                
                List<Map<String, Object>> teacherIdsList = new ArrayList<>();
                for (Object[] record : allTeacherIds) {
                    Map<String, Object> rec = new HashMap<>();
                    rec.put("id", record[0]);
                    rec.put("title", record[1]);
                    rec.put("teacher_id", record[2]);
                    teacherIdsList.add(rec);
                }
                result.put("allTeacherIds", teacherIdsList);
                result.put("totalRecords", allTeacherIds.size());
            } catch (Exception e) {
                log.error("查询所有teacher_id失败", e);
                result.put("allTeacherIdsError", e.getMessage());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("SQL调试查询失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("SQL调试查询失败: " + e.getMessage());
        }
    }

    /**
     * 调试端点：查看所有教学计划记录
     */
    @GetMapping("/all-debug")
    public ResponseEntity<?> allRecordsDebug() {
        try {
            log.info("查询所有教学计划记录");
            
            List<TeachingPlan> allPlans = teachingPlanService.findAll();
            log.info("总共找到{}条记录", allPlans.size());
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", allPlans);
            result.put("count", allPlans.size());
            
            // 打印每条记录的教师ID
            for (TeachingPlan plan : allPlans) {
                log.info("教学计划ID: {}, 标题: {}, 教师ID: {}", 
                         plan.getId(), plan.getTitle(), plan.getTeacherId());
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询所有记录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取教师所有教学计划（历史记录）
     */
    @GetMapping("/history")
    public ResponseEntity<List<TeachingPlan>> getTeacherPlans(@RequestParam String teacherId) {
        List<TeachingPlan> plans = teachingPlanService.findByTeacherId(teacherId);
        return ResponseEntity.ok(plans);
    }
} 